//
//  SetGestureLockViewController.m
//  HuaMuJinRong
//
//  Created by Cindy on 15/12/25.
//  Copyright (c) 2015年 EIMS. All rights reserved.
//

#import "SetGestureLockViewController.h"
#import "GestureLockView.h"
#import "ColorTools.h"
#import "TabViewController.h"
#import "GesDatabase.h"
#import "NSString+UserInfo.h"
#import "ExperienceViewController.h"

@interface SetGestureLockViewController ()<GestureLockViewDelegate>
{
    NSMutableArray *passwordArr;
}
@property (nonatomic, strong) GestureLockView *lockView;
@property (nonatomic, strong) UILabel *againLabel;
@property (nonatomic, strong) UIImageView *headView;
@property (nonatomic, strong) UILabel *nameLabel;

@end

@implementation SetGestureLockViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
   
    
    [self initView];
    
    [self initData];
    
    [self backBtn];
}

/**
 * 初始化返回按钮
 */
- (void)backBtn
{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(15, 25, 20, 20);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    [self.view addSubview:backBtn];
    [backBtn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    
    
}
- (void)clickBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initView
{
    self.view.backgroundColor = SETCOLOR(24, 50, 68, 1.0);

    
    CGFloat space = MSHIGHT <= 568?0:15;
    
    CGFloat lockViewTop = MSHIGHT <= 480?(self.view.frame.size.height*0.5+35):(self.view.frame.size.height*0.5+60+space);
    
    _headView = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width*0.5-37.5, 60+space, 75, 75)];
    _headView.layer.cornerRadius = 37.5;
    _headView.userInteractionEnabled = NO;
    _headView.layer.masksToBounds = YES;
    [self.view addSubview:_headView];
    
    
    // 加载上次登陆的头像或者默认的头像
    NSString *imageUrl = [[AppDefaultUtil sharedInstance] getDefaultHeaderImageUrl];
    [_headView sd_setImageWithURL:[NSURL URLWithString:imageUrl]
                 placeholderImage:[UIImage imageNamed:@"default_head"]];
    
    
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(_headView.frame)+5, MSWIDTH-20, 30)];
    NSString *userName = [[AppDefaultUtil sharedInstance]getDefaultAccount];
    if (userName.length > 10) {
        userName = [NSString phoneNumToAsterisk:userName];
    }
    _nameLabel.text = userName;
    
    _nameLabel.textAlignment = NSTextAlignmentCenter;
    _nameLabel.tag = 110;
    _nameLabel.font = [UIFont systemFontOfSize:15.0f];
    _nameLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:_nameLabel];
    
    
    
    _againLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, MSHIGHT-lockViewTop-40, self.view.frame.size.width, 30)];
    _againLabel.font = [UIFont systemFontOfSize:14.0f];
    _againLabel.tag = 100;
    _againLabel.textAlignment = NSTextAlignmentCenter;
    _againLabel.textColor = [UIColor whiteColor];
    _againLabel.text = @"设置手势密码";
    [self.view addSubview:_againLabel];
    
    
    self.lockView = [[GestureLockView alloc] initWithFrame:CGRectMake(0, -70, self.view.bounds.size.width, self.view.bounds.size.height)];
    self.lockView.normalGestureNodeImage = [UIImage imageNamed:@"gesture_node_normal"];
    self.lockView.selectedGestureNodeImage = [UIImage imageNamed:@"gesture_node_selected"];
    self.lockView.lineColor = [KColor colorWithAlphaComponent:1.0];
    self.lockView.lineWidth = 2;
    self.lockView.delegate = self;
    if(self.view.frame.size.height == 480) {
        self.lockView.contentInsets = UIEdgeInsetsMake(self.view.frame.size.height*0.5+30, self.view.frame.size.width*0.13, 5, self.view.frame.size.width*0.13);
    }else {
        self.lockView.contentInsets = UIEdgeInsetsMake(self.view.frame.size.height*0.5+30, self.view.frame.size.width*0.12, 25, self.view.frame.size.width*0.12);
    }
    [self.view addSubview:self.lockView];
    
    
    
    UILabel *footLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-70, self.view.frame.size.width, 30)];
    footLabel.font = [UIFont systemFontOfSize:14.0f];
    footLabel.text = @"手势密码在您每次打开程序时启用";
    footLabel.textAlignment = NSTextAlignmentCenter;
    footLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:footLabel];
}

- (void)initData
{
    passwordArr = [[NSMutableArray alloc] init];
}


- (void)gestureLockView:(GestureLockView *)gestureLockView didBeginWithPasscode:(NSString *)passcode
{
    self.lockView.selectedGestureNodeImage = [UIImage imageNamed:@"gesture_node_selected"];
    
    self.lockView.lineColor = KColor;
    
    _againLabel.textColor = KColor;
    
    _againLabel.text = @"";
    
    [self.lockView setNeedsDisplay];
}


- (void)gestureLockView:(GestureLockView *)gestureLockView didEndWithPasscode:(NSString *)passcode
{
    
    DLOG(@"手势密码为:%@",passcode);  DLOG(@"手势密码为:%@",passcode);
    UILabel *label1 = (UILabel *)[self.view viewWithTag:103];
    [label1 removeFromSuperview];
    
    if (passcode.length < 7) {
        _againLabel.text = @"至少连接4个点，请重新输入!";
        _againLabel.textColor = [UIColor redColor];
        [CommonClass shakeAnimationForView:_againLabel];
        
        
        self.lockView.selectedGestureNodeImage = [UIImage imageNamed:@"gesture_wrong_selected"];
        self.lockView.lineColor = KWrongLineColor;
        [self.lockView setNeedsDisplay];
        
        
    }else {
        [passwordArr insertObject:passcode atIndex:0];
        
        if ([passwordArr count]==1) {
            
            _againLabel.text = @"请再绘制一遍确认手势密码";
            
            
        }else if ([passwordArr count]==2) {
            
            if ([[passwordArr objectAtIndex:0] isEqualToString:[passwordArr objectAtIndex:1]]) {
                
                //存储手势密码
                
                NSString *despwd = [NSString encrypt3DES:[passwordArr objectAtIndex:0] key:DESkey];
                
                [[GesDatabase getInstance]insertOrUpdateUserInfoWithUserName:[[AppDefaultUtil sharedInstance] getDefaultAccount] loginPwd:@"" gesturePwd:despwd gestureState:@"1"];
                
                // 设置成功
                [self setSuccess];
                [SVProgressHUD showSuccessWithStatus:@"手势密码设置成功!"];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * 600000000ull)), dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                });
                
            }else {
                DLOG(@"密码不一致！！！！！");
                _againLabel.text = @"请重新设置手势密码！";
                _againLabel.textColor = [UIColor redColor];
                [CommonClass shakeAnimationForView:_againLabel];
                
                [passwordArr removeAllObjects];
                
                self.lockView.selectedGestureNodeImage = [UIImage imageNamed:@"gesture_wrong_selected"];
                self.lockView.lineColor = KWrongLineColor;
                [self.lockView setNeedsDisplay];
            }
        }
    }
}

-(void) setSuccess
{
    if (!_isGoExperience) {
        if (self.backType == 1) {
            //登录进入，返回首页
            //        UIViewController *rootVc = [AppDelegateInstance.window.rootViewController.tabBarController selectedViewController];
            //        if (rootVc.presentingViewController) {
            //            [rootVc.presentingViewController dismissViewControllerAnimated:YES completion:nil];
            //        }else {
            //            [rootVc.navigationController popViewControllerAnimated:YES];
            //        }
            //
            //        [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
            //
            //        TabViewController *tabViewController = [TabViewController shareTableView];
            //        tabViewController.selectedIndex = 0;
            //        AppDelegateInstance.window.rootViewController = tabViewController;
            
            
            
            [self dismissViewControllerAnimated:YES completion:nil];
            AppDelegateInstance.window.rootViewController = nil;
            
            TabViewController *tabViewController = [[TabViewController alloc] init];
            AppDelegateInstance.window.rootViewController = tabViewController;
            
        }else if (self.backType == 2) {
            self.navigationController.navigationBarHidden = NO;
            [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
        }else{
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        
    }else { //注册之后去体验标页面
        
        ExperienceViewController *experience = [[ExperienceViewController alloc] init];
        experience.isFirstLogin = YES;
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:experience];
        [self presentViewController:navi animated:YES completion:^{
            AppDelegateInstance.isFirstLogin = NO;
            AppDelegateInstance.firstLoginNameStr = @"";
        }];
    }
    
    
}


@end
